//
//  UserViewController.m
//  SnailPost
//
//  Created by 抠泥ser on 16/3/7.
//  Copyright © 2016年 抠泥ser. All rights reserved.
//

#import "UserViewController.h"
#import "UIColor+Wonderful.h"
#import "ShouCangViewController.h"
#import "LoginViewController.h"

#import "CollectViewController.h"
#import "PictureViewController.h"
#import <TencentOpenAPI/TencentOAuth.h> // 登录
#import "WeatherViewController.h"
#import "Scan_VC.h"


@interface UserViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSArray *dataArr;
@property (nonatomic, strong)NSArray *arr;
@property (nonatomic, strong)NSArray *firstArr;
@property (nonatomic, strong)NSArray *secondArr;
@property (nonatomic, assign)CGFloat cache; //缓存的数值
@property (nonatomic, strong)UIAlertView *cacheAlert; //清除时的弹窗
@property (nonatomic, strong)NSString *str;//缓存的图标

@property (nonatomic, strong)TencentOAuth *tencentOAuth;/**< qq登录 */

@property (nonatomic, strong) UILabel *name;
@property (nonatomic, strong) UIImageView *touxiang;

@end


@implementation UserViewController




- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor gainsboroColor];
    self.navigationItem.title = @"我的";
    self.navigationController.navigationBar.translucent = NO;
//****** tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 334, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _tableView.backgroundColor =[UIColor clearColor];
    _tableView.delegate =self;
    _tableView.dataSource =self;
//    _tableView.scrollEnabled = NO;

    _tableView.showsVerticalScrollIndicator = NO;
//    _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 270)];
    
    [self.view addSubview:_tableView];
    

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(270, 0, 0, 0));
        
    

        
    }];
    
    
//    [_tableView registerClass:[UserTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    
    //我的背景墙设置
    
    UIImageView *backgroud = [UIImageView new];

//    backgroud.image = [UIImage imageNamed:@"backgroud"];
    backgroud.backgroundColor = [UIColor clearColor];
    [self.view addSubview:backgroud];

    
    //背景是图片,得开启用户交互.
    backgroud.userInteractionEnabled = YES;
    
    [backgroud mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(0);
        make.left.equalTo(self.view ).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.height.mas_equalTo(270);
    }];
    //    self.tableView.tableHeaderView = backgroud;
    
    
//    设置背景墙的高斯模糊以及模糊样式
    UIBlurEffect *back =[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *backVc =[[UIVisualEffectView alloc]initWithEffect:back];
    backVc.frame = CGRectMake(0, 0, self.view.frame.size.width, 270);
//        [backVc mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(self.view).with.offset(0);
//            make.left.equalTo(self.view).with.offset(0);
//            make.width.mas_equalTo(self.view);
//            make.height.mas_equalTo(@340);
//        }];
    backVc.alpha = 0.75;
    [backgroud addSubview:backVc];

    
//******** 头像
    self.touxiang =[[UIImageView alloc]initWithFrame:CGRectMake(WIDTH / 2,667 / 2, 100, 100)];
    _touxiang.center = CGPointMake(WIDTH / 2, 270 / 2.3);
    _touxiang.layer.cornerRadius = 50;
    _touxiang.clipsToBounds = YES;
    _touxiang.backgroundColor = [UIColor whiteColor];
    _touxiang.image = [UIImage imageNamed:@"touxiang2"];
    [backgroud addSubview:_touxiang];
    
    UIButton *button = [UIButton buttonWithType: UIButtonTypeCustom];
    button.frame = CGRectMake(WIDTH / 2,667 / 2, 100, 100);
    button.center = CGPointMake(WIDTH / 2, 270 / 2.3);
    button.backgroundColor = [UIColor clearColor];
    [backgroud addSubview:button];
    [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.name = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 375, 40)];
    _name.center = CGPointMake(375/ 2 , 270 / 1.3);
//    name.backgroundColor = [UIColor greenColor];
    _name.font = [UIFont fontWithName:@"Helvetica-Bold" size:19];
    _name.textAlignment = NSTextAlignmentCenter;
    [backgroud addSubview:_name];
    
    
    //设置按钮
   
    
    
    self.arr = @[@"我的收藏",@"扫一扫"];
    self.dataArr = @[@"夜间模式",@"清除缓存",@"关于我们",@"天气预报"];
    self.firstArr = @[@"shoucang",@"sao"];
    self.secondArr = @[@"night",@"clear",@"about",@"tianqi"];
    
    
    //处理数据
    [self data];
   
    
}


- (void)data
{
    
}


//每个分区的rows数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    }else if(section == 1){
        return 3;
    }else{
        return 2;
    }
}

//分区个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

//- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
//{
//    return 3;
//}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.backgroundColor = [UIColor clearColor];

    //如果没有这个cell,自动添加补位
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cell"];
        [cell NightWithType:UIViewColorTypeNormal];
    }
    
    if (indexPath.section == 0) {
        cell.imageView.image = [UIImage imageNamed:_firstArr[indexPath.row]];
        cell.textLabel.text = _arr[indexPath.row];
        [cell.textLabel NightWithType:UIViewColorTypeNormal];
    }
    if (indexPath.section == 1) {
        cell.imageView.image = [UIImage imageNamed:_secondArr[indexPath.row]];
        cell.textLabel.text = _dataArr[indexPath.row];
        [cell.textLabel NightWithType:UIViewColorTypeNormal];
        if (indexPath.row == 0) {
            UISwitch *open =[[UISwitch alloc]init];
            [open addTarget:self action:@selector(dayAndnight:) forControlEvents:UIControlEventTouchUpInside];
            cell.accessoryView = open;
            NSUserDefaults *userDefaules = [NSUserDefaults standardUserDefaults];
            open.on = [userDefaules boolForKey:@"switch"];
        }
 
    }if (indexPath.section == 2) {
        if (indexPath.row == 0) {
    
            cell.imageView.image = [UIImage imageNamed:_secondArr[3]];
            cell.textLabel.text = _dataArr[3];
            [cell.textLabel NightWithType:UIViewColorTypeNormal];
        }
        if (indexPath.row == 1) {
            cell.imageView.image = [UIImage imageNamed:@"tupian"];
            cell.textLabel.text = @"更换主题";
            [cell.textLabel NightWithType:UIViewColorTypeNormal];
        }
    }
    return cell;
}
#pragma mark - 实现真夜间模式
-(void)dayAndnight:(UISwitch *)open
{
    [ThemeManage shareThemeManage].isNight = ![ThemeManage shareThemeManage].isNight;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeColor" object:nil];
    [[NSUserDefaults standardUserDefaults] setBool:[ThemeManage shareThemeManage].isNight forKey:@"night"];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setBool:open.on forKey:@"switch"];

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

//点击实现方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //让点击的灰色迅速消失
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            self.hidesBottomBarWhenPushed = YES;
            ShouCangViewController *vc =[[ShouCangViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
            self.hidesBottomBarWhenPushed = NO;
        }
        if (indexPath.row == 1) {
            self.hidesBottomBarWhenPushed = YES;
            Scan_VC *erweima = [[Scan_VC alloc] init];
            [self.navigationController pushViewController:erweima animated:YES];
            self.hidesBottomBarWhenPushed = NO;
        }
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
//            真夜间模式
        }
        
        
        if ( indexPath.row == 1) {
            //计算缓存
            //创建管理器对象
            NSFileManager *fileManager =[NSFileManager defaultManager];
            //获取沙盒路径
            NSString *catch =NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
            if ([fileManager fileExistsAtPath:catch]) {
                NSArray *files = [fileManager subpathsAtPath:catch];
                
                //遍历所有文件
                for(NSInteger i = 0; i < files.count; i++) {
                    NSString *filePath = [catch stringByAppendingPathComponent:files[i]];
                    
                    //获取文件大小
                    float k =[[fileManager attributesOfItemAtPath:filePath error:nil]fileSize];
                    self.cache = self.cache + k;
                }
            }
            NSString *message =[NSString stringWithFormat:@"是否确认清除%.2lfM内存",self.cache / 1024 / 1024];
            
            
            if ([[[UIDevice currentDevice]systemVersion]floatValue] > 8.0) {
                // 提示是不是清除缓存
                UIAlertController *alertView =[UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
                // 取消
                UIAlertAction *cancel =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                
                //确定
                UIAlertAction *certain =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    //清除掉cache文件夹
                    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
                    NSFileManager *fManage = [NSFileManager defaultManager];
                    [fManage removeItemAtPath:path error:nil];
                    
                    //将缓存的值为0
                    self.cache = 0;
                }];
                [alertView addAction:cancel];
                [alertView addAction:certain];
                
                [self presentViewController:alertView animated:YES completion:^{
                    
                }];
            }

            
        }
        if (indexPath.row == 2) {
            
            CollectViewController *sec =[[CollectViewController alloc]init];
            UINavigationController *navi =[[UINavigationController alloc]initWithRootViewController:sec];
            [self presentViewController:navi animated:YES completion:^{
                
            }];
            
            //关于我们
        }
    }
    if (indexPath.section == 2) {
        if (indexPath.row == 1) {
            PictureViewController *sef =[[PictureViewController alloc]init];
            [self.navigationController pushViewController:sef animated:YES];
        }
        if (indexPath.section == 2 && indexPath.row == 0) {
            WeatherViewController *weVC = [[WeatherViewController alloc] init];
            
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:weVC animated:YES];
            self.hidesBottomBarWhenPushed = NO;
        }
        
    }

}
#pragma mark - qq登录按钮
- (void)click:(UIButton *)btn
{
    _tencentOAuth = [[TencentOAuth alloc] initWithAppId:@"1105182787" andDelegate:self];
    
    if (_tencentOAuth.accessToken) {
        [_tencentOAuth setAccessToken:_tencentOAuth.accessToken];
        [_tencentOAuth setOpenId:_tencentOAuth.openId];
        [_tencentOAuth setExpirationDate:_tencentOAuth.expirationDate];
        
    }else{
        NSArray* permissions = [NSArray arrayWithObjects:
                                kOPEN_PERMISSION_GET_USER_INFO,
                                kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                                kOPEN_PERMISSION_ADD_ALBUM,
                                kOPEN_PERMISSION_ADD_ONE_BLOG,
                                kOPEN_PERMISSION_ADD_SHARE,
                                kOPEN_PERMISSION_ADD_TOPIC,
                                kOPEN_PERMISSION_CHECK_PAGE_FANS,
                                kOPEN_PERMISSION_GET_INFO,
                                kOPEN_PERMISSION_GET_OTHER_INFO,
                                kOPEN_PERMISSION_LIST_ALBUM,
                                kOPEN_PERMISSION_UPLOAD_PIC,
                                kOPEN_PERMISSION_GET_VIP_INFO,
                                kOPEN_PERMISSION_GET_VIP_RICH_INFO,
                                nil];
        
        [_tencentOAuth authorize:permissions inSafari:NO];
    }
    
}

#pragma mark - qq回调协议
- (void)getUserInfoResponse:(APIResponse*) response
{
    // 三方登陆获取的头像数据
    //    "figureurl_qq_1" = "http://q.qlogo.cn/qqapp/1105164233/877B7E00A3B8F2A5CEF1CE00E9883BAB/40";
    //    "figureurl_qq_2" = "http://q.qlogo.cn/qqapp/1105164233/877B7E00A3B8F2A5CEF1CE00E9883BAB/100";
    NSLog(@"%@",response.jsonResponse);//打印用户信息
    NSLog(@"%@",[response.jsonResponse objectForKey:@"nickname"]);//打印用户昵称
    
    NSString *nameString = [response.jsonResponse objectForKey:@"nickname"];
    self.name.text = nameString;
    
    NSString *imageString = [NSString stringWithFormat:@"%@",[response.jsonResponse objectForKey:@"figureurl_qq_2"]];//用户头像
    [self.touxiang sd_setImageWithURL:[NSURL URLWithString:imageString]];
    // 单例保存
    [[NSUserDefaults standardUserDefaults] setObject:nameString forKey:@"name"];
    [[NSUserDefaults  standardUserDefaults] setObject:imageString forKey:@"image"];
    NSLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"image"]);
    
}

-(void)tencentDidLogin
{
    //    _labelTitle.text = @"登录完成";
    if (_tencentOAuth.accessToken && 0 != [_tencentOAuth.accessToken length])
    {
        //  记录登录用户的OpenID、Token以及过期时间
        //        _labelAccessToken.text = _tencentOAuth.accessToken;
        NSLog(@"%@", _tencentOAuth.accessToken);
        [_tencentOAuth accessToken];
        [_tencentOAuth openId];
        [_tencentOAuth expirationDate];
        
        [_tencentOAuth getUserInfo];
        NSLog(@"登陆成功");
    }
    else
    {
        //        _labelAccessToken.text = @"登录不成功 没有获取accesstoken";
        NSLog(@"登陆不成功, 没有获取accesstoken");
    }
}

-(void)tencentDidNotLogin:(BOOL)cancelled
{
    if (cancelled)
    {
        //        _labelTitle.text = @"用户取消登录";
        NSLog(@"用户取消登陆");
    }
    else
    {
        //        _labelTitle.text = @"登录失败";
        NSLog(@"登陆失败");
    }
}
- (void)tencentDidNotNetWork
{
    NSLog(@"网络问题登录失败");
}
- (NSArray *)getAuthorizedPermissions:(NSArray *)permissions
                      withExtraParams:(NSDictionary *)extraParams
{
    NSLog(@"~~~~~~~%@\n %@", permissions, extraParams);
    return permissions;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/



@end

